<template>
  <div>
    <el-divider content-position="left">用户信息</el-divider>
    <div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名" style="width: 30%">
          <el-input v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <div class="block" style="margin-right: 80%">
            <el-date-picker
              v-model="dateBetween"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item style="margin-right: 70%">
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider content-position="left"></el-divider>
    <div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column prop="userName" label="用户名" width="120">
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="100"> </el-table-column>
        <el-table-column label="创建时间" width="120">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>

        <el-table-column label="更新时间" width="120">
          <template slot-scope="scope">{{ scope.row.updateTime }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="180">
          <template slot-scope="scope">
            <div v-if="scope.row.status !== 2">
              <el-switch
                v-model="scope.row.status"
                active-text="开通"
                inactive-text="未开通"
                :active-value="1"
                :inactive-value="0"
                @change="handleSwitchChange(scope.row.id, value)"
              >
              </el-switch>
            </div>
            <div v-else><el-tag> 管理员 </el-tag></div>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="到期时间">
          <template slot-scope="scope">
            <div class="block">
              <el-date-picker
                v-model="scope.row.endTime"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; margin-left: 10%">
        <el-button @click="toggleSelection([tableData[0]])"
          >切换第一行</el-button
        >
        <el-button @click="toggleSelection()">取消选择</el-button>
        <el-button @click="updateUsers()">更新</el-button>
        <el-button @click="deleteUser()">删除</el-button>
        <el-button @click="updateEndTime()">更新时间</el-button>
      </div>
    </div>
    <div style="margin-top: 2%">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="size"
        background
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getUserList } from "@/api/user";
import { deleteUser } from "@/api/user";
import { updateUser } from "@/api/user";
import { updateUserViewEndTimeById } from "@/api/userView";
export default {
  data() {
    return {
      form: {
        id: "",
        userName: "",
        age: "",
        createTime: "",
        updateTime: "",
        status: "",
      },
      dateBetween: "",
      tableData: [
        {
          id: "",
          userName: "",
          age: "",
          createTime: "",
          updateTime: "",
          status: "",
          endTime: "",
        },
      ],
      multipleSelection: [],
      page: 1,
      size: 10,
      total: 0,
      startTime: "",
      endTime: "",
      intervalId: null,
      value: 0,
    };
  },
  methods: {
    getUserLists() {
      const u = {
        userName: this.userName === "" ? null : this.form.userName,
        startTime: this.dateBetween[0] === "" ? null : this.dateBetween[0],
        endTime: this.dateBetween[1] === "" ? null : this.dateBetween[1],
        page: this.page,
        size: this.size,
      };
      getUserList(u).then((res) => {
        console.log(res);
        this.tableData = res.data.list;
        this.total = res.data.total;
        // this.tableData.status === 1 ? (this.value = 1) : (this.value = 0);
      });
    },
    onSubmit() {
      this.getUserLists();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //console.log(val);
    },
    handleCurrentChange(val) {
      const upage = {
        userName: this.userName === "" ? null : this.form.userName,
        startTime: this.startTime === "" ? null : this.form.startTime,
        endTime: this.endTime === "" ? null : this.form.endTime,
        page: val,
        size: this.size,
      };
      getUserList(upage).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
      });
    },
    // 页面大小改变时触发
    handleSizeChange(val) {
      this.size = val;
      // 可以在这里进行数据请求，获取新的数据
    },
    deleteUser() {
      for (var i = 0; i < this.multipleSelection.length; i++) {
        const newId = {
          id: this.multipleSelection[i].id,
        };

        deleteUser(newId).then((res) => {
          if (res.code === 0) {
            this.getUserLists();
            this.$message({
              showClose: true,
              message: "删除成功",
            });
          } else {
            this.$message({
              showClose: true,
              message: "删除失败",
              type: "warning",
            });
          }
        });
      }
    },

    updateUsers() {
      const le = this.multipleSelection.length;
      if (le > 1) {
        this.$message({
          showClose: true,
          message: "只能选择一个选项进行修改",
          type: "warning",
        });
        return;
      } else if (le === 0) {
        this.$message({
          showClose: true,
          message: "请选择一个选项进行修改",
          type: "warning",
        });
        return;
      }
      const co = {
        id: this.multipleSelection[0].id,
        userName: this.multipleSelection[0].userName,
        age: this.multipleSelection[0].age,
        status: this.multipleSelection[0].status,
      };
      // http://192.168.142.30:8080
      window.open("http://192.168.142.30:8080/#/AdminUpdateUser?id=" + co.id);
      //router.push({ name: "AdminUpdateUser", params: co });
    },
    checkCookie() {
      //const newCookieValue = this.getCookie("cookie_update"); // 替换'myCookieName'为你要监听的cookie名称
      const newCookieValue = this.$cookies.get("cookie_update");
      //console.log("newCookieValue", newCookieValue);
      if (newCookieValue) {
        this.$cookies.remove("cookie_update");
        // 这里可以添加cookie变化时的处理逻辑
        //console.log("Cookie changed to:");
        this.getUserLists();
      }
    },
    //更新用户状态
    async handleSwitchChange(id, value) {
      console.log("Switch id changed to:", id);
      console.log("Switch value changed to:", value);
      const con = {
        id: id,
        status: value ? 0 : 1,
      };
      const response = await updateUser(con);
      if (response.code === 0) {
        this.$message({
          showClose: true,
          message: "状态修改成功",
        });
      } else {
        this.$message({
          showClose: true,
          message: "更新失败",
          type: "warning",
        });
        return;
      }
    },
    async updateEndTime() {
      const le = this.multipleSelection.length;
      if (le > 1) {
        this.$message({
          showClose: true,
          message: "只能选择一个选项进行修改",
          type: "warning",
        });
        return;
      } else if (le === 0) {
        this.$message({
          showClose: true,
          message: "请选择一个选项进行修改",
          type: "warning",
        });
        return;
      }
      // console.log(
      //   "this.multipleSelection[0].endTime==>",
      //   this.multipleSelection[0].endTime
      // );
      //console.log("===>", this.multipleSelection[0].endTimeg);
      //this.forEndTime = this.multipleSelection[0].endTimeg;
      //console.log(this.forEndTime);
      const end = {
        id: this.multipleSelection[0].id,
        endTime: this.multipleSelection[0].endTime,
      };
      console.log("end==>", end);

      const response = await updateUserViewEndTimeById(end);
      if (response.code === 0) {
        this.$message({
          showClose: true,
          message: "修改成功",
        });
      } else {
        this.$message({
          showClose: true,
          message: "更新失败",
          type: "warning",
        });
        return;
      }
    },
  },

  created() {
    this.getUserLists();
    this.intervalId = setInterval(this.checkCookie, 2000); // 每5秒检查一次cookie
  },
  destroyed() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
  mounted() {},
};
</script>
